package applicationAlibi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class Image
 */
public class Image extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Image() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext sc = getServletContext();
		System.out.println("image");
		String wanted;
		try {
			wanted = new URL(request.getRequestURL().toString()).getFile();

			String filename = getServletContext().getRealPath("./")+ "/../server/default/data" + wanted;

			System.out.println();
			String mimeType = sc.getMimeType(filename);

			response.setContentType(mimeType);

			File file = new File(filename);

			response.setContentLength((int) file.length());

			try {
				FileInputStream in;
				in = new FileInputStream(file);

				OutputStream out = response.getOutputStream();

				byte[] buf = new byte[1024];
				int count = 0;
				while ((count = in.read(buf)) >= 0) {
					out.write(buf, 0, count);
				}
				in.close();
				out.close();
			} catch (FileNotFoundException e) {
				System.err.println("Petit probleme : non trouve " + filename);
			} catch (IOException e) {
				System.err.println("Petit probleme IOException sur " + filename);
			}
		} catch (MalformedURLException e) {
			System.err.println(request.getRequestURL().toString() + " est mal formee !");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
